package com.liaoban.app.ui.base;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.LayoutRes;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.liaoban.app.R;
import com.liaoban.app.api.type.event.LogoutEvent;
import com.liaoban.app.constants.Constant;
import com.liaoban.app.exception.AppException;
import com.liaoban.app.helper.BaseHelper;
import com.liaoban.app.helper.DialogHelper;
import com.liaoban.app.helper.ToastHelper;
import com.liaoban.app.ui.login.LoginActivity;
import com.liaoban.app.util.CommonUtils;
import com.liaoban.app.util.RxUtils;
import com.trello.rxlifecycle2.components.support.RxFragment;
import com.umeng.analytics.MobclickAgent;

import org.greenrobot.eventbus.EventBus;

import butterknife.ButterKnife;
import butterknife.Unbinder;
import io.reactivex.Observable;
import io.reactivex.functions.Consumer;

/**
 * Fragment基类
 * Created by ybc on 2017/7/5.
 */

public abstract class BaseFragment extends RxFragment {

    protected ProgressDialog mRunningDialog;

    // 设置Fragment的布局id
    @LayoutRes
    protected abstract int getLayoutResID();

    //此方法中进行View内容的初始化以及监听的绑定,此时View已经通过注入获取.
    protected abstract void initView(View contentView);

    Unbinder unbinder;

    //是否使用EventBus,如果使用EventBus,则子类必须要有public的onEvent方法
    private boolean mNeedOnBus;

    protected void setNeedOnBus(boolean needOnBus) {
        mNeedOnBus = needOnBus;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View contentView = null;

        int layoutResID = getLayoutResID();
        if (layoutResID > 0) {
            contentView = inflater.inflate(layoutResID, null);
            unbinder = ButterKnife.bind(this, contentView);
            initView(contentView);
        }
        if (mNeedOnBus) {
            EventBus.getDefault().register(this);
        }
        return contentView;
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        BaseHelper.initSwipeRefreshLayoutColor(view);
    }

    /**
     * 利用反射获取状态栏高度
     *
     * @return
     */
    protected int getStatusBarHeight() {
        int result = 0;
        //获取状态栏高度的资源id
        int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            result = getResources().getDimensionPixelSize(resourceId);
        }
        return result;
    }

    /**
     * 设置距离顶部距离
     * 如果API版本大于21可设置沉浸式距离
     *
     * @param contentView
     */
    protected void setMarginTop(View contentView, int num) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            contentView.setPadding(0, num, 0, 0);
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart(getClass().getSimpleName());
    }

    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd(getClass().getSimpleName());
    }

    @Override
    public void onDestroyView() {
        if (mNeedOnBus) {
            EventBus.getDefault().unregister(this);
        }
        unbinder.unbind();
        super.onDestroyView();
    }

    //用于执行异步任务
    protected <T> void startTask(Observable<T> observable, Consumer<? super T> onNext, Consumer<? super Throwable> onError) {
        observable.compose(bindToLifecycle()).compose(RxUtils.ioToMainTread()).subscribe(onNext, onError, this::onComplete);
    }

    //用于执行异步任务
    protected <T> void startTask(Observable<T> observable, Consumer<? super T> onNext) {
        observable.compose(bindToLifecycle()).compose(RxUtils.ioToMainTread()).subscribe(onNext, this::defOnError, this::onComplete);
    }

    private void onComplete() {
        dismissRunningDialog();
    }

    protected void defOnError(Throwable t) {
        dismissRunningDialog();
        if (t instanceof AppException) {
            ToastHelper.show(getActivity(), ((AppException) t).getMsg());
            if (Constant.LOGIN_STATUS == ((AppException) t).getCode()) {
                CommonUtils.logout(getActivity());
                EventBus.getDefault().post(new LogoutEvent());
                startActivity(new Intent(getActivity(), LoginActivity.class));
            }
        } else {
            ToastHelper.show(getActivity(), t.getMessage());
        }
    }

    protected void showRunningDialog() {
        if (mRunningDialog == null) {
            mRunningDialog = DialogHelper.getProgressDialog(getActivity(), R.string.running);
        } else {
            mRunningDialog.setMessage(getString(R.string.running));
        }
        mRunningDialog.show();
    }

    protected void showRunningDialog(int resId) {
        if (mRunningDialog == null) {
            mRunningDialog = DialogHelper.getProgressDialog(getActivity(), resId);
        } else {
            mRunningDialog.setMessage(getString(resId));
        }
        mRunningDialog.show();
    }

    protected void dismissRunningDialog() {
        if (mRunningDialog != null && mRunningDialog.isShowing()) {
            mRunningDialog.dismiss();
        }
    }
}
